{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -- 将数据框命名为crime\n",
    "# -- 每一列(column)的数据类型是什么样的？\n",
    "# -- 将Year的数据类型转换为 datetime64\n",
    "# -- 将列Year设置为数据框的索引\n",
    "# -- 删除名为Total的列\n",
    "# -- 按照Year（每十年）对数据框进行分组并求和\n",
    "# -- 何时是美国历史上生存最危险的年代？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "#将数据框命名为drinks\n",
    "crime = pd.read_csv('data/US_Crime_Rates_1960_2014.csv',index_col=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "Index: 55 entries, 0 to 54\n",
      "Data columns (total 12 columns):\n",
      " #   Column              Non-Null Count  Dtype\n",
      "---  ------              --------------  -----\n",
      " 0   Year                55 non-null     int64\n",
      " 1   Population          55 non-null     int64\n",
      " 2   Total               55 non-null     int64\n",
      " 3   Violent             55 non-null     int64\n",
      " 4   Property            55 non-null     int64\n",
      " 5   Murder              55 non-null     int64\n",
      " 6   Forcible_Rape       55 non-null     int64\n",
      " 7   Robbery             55 non-null     int64\n",
      " 8   Aggravated_assault  55 non-null     int64\n",
      " 9   Burglary            55 non-null     int64\n",
      " 10  Larceny_Theft       55 non-null     int64\n",
      " 11  Vehicle_Theft       55 non-null     int64\n",
      "dtypes: int64(12)\n",
      "memory usage: 5.6 KB\n"
     ]
    }
   ],
   "source": [
    "#每一列(column)的数据类型是什么样的？\n",
    "crime.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Total</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960-01-01</th>\n",
       "      <td>179323175</td>\n",
       "      <td>3384200</td>\n",
       "      <td>288460</td>\n",
       "      <td>3095700</td>\n",
       "      <td>9110</td>\n",
       "      <td>17190</td>\n",
       "      <td>107840</td>\n",
       "      <td>154320</td>\n",
       "      <td>912100</td>\n",
       "      <td>1855400</td>\n",
       "      <td>328200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1961-01-01</th>\n",
       "      <td>182992000</td>\n",
       "      <td>3488000</td>\n",
       "      <td>289390</td>\n",
       "      <td>3198600</td>\n",
       "      <td>8740</td>\n",
       "      <td>17220</td>\n",
       "      <td>106670</td>\n",
       "      <td>156760</td>\n",
       "      <td>949600</td>\n",
       "      <td>1913000</td>\n",
       "      <td>336000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1962-01-01</th>\n",
       "      <td>185771000</td>\n",
       "      <td>3752200</td>\n",
       "      <td>301510</td>\n",
       "      <td>3450700</td>\n",
       "      <td>8530</td>\n",
       "      <td>17550</td>\n",
       "      <td>110860</td>\n",
       "      <td>164570</td>\n",
       "      <td>994300</td>\n",
       "      <td>2089600</td>\n",
       "      <td>366800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1963-01-01</th>\n",
       "      <td>188483000</td>\n",
       "      <td>4109500</td>\n",
       "      <td>316970</td>\n",
       "      <td>3792500</td>\n",
       "      <td>8640</td>\n",
       "      <td>17650</td>\n",
       "      <td>116470</td>\n",
       "      <td>174210</td>\n",
       "      <td>1086400</td>\n",
       "      <td>2297800</td>\n",
       "      <td>408300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1964-01-01</th>\n",
       "      <td>191141000</td>\n",
       "      <td>4564600</td>\n",
       "      <td>364220</td>\n",
       "      <td>4200400</td>\n",
       "      <td>9360</td>\n",
       "      <td>21420</td>\n",
       "      <td>130390</td>\n",
       "      <td>203050</td>\n",
       "      <td>1213200</td>\n",
       "      <td>2514400</td>\n",
       "      <td>472800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Population    Total  Violent  Property  Murder  Forcible_Rape  \\\n",
       "Year                                                                        \n",
       "1960-01-01   179323175  3384200   288460   3095700    9110          17190   \n",
       "1961-01-01   182992000  3488000   289390   3198600    8740          17220   \n",
       "1962-01-01   185771000  3752200   301510   3450700    8530          17550   \n",
       "1963-01-01   188483000  4109500   316970   3792500    8640          17650   \n",
       "1964-01-01   191141000  4564600   364220   4200400    9360          21420   \n",
       "\n",
       "            Robbery  Aggravated_assault  Burglary  Larceny_Theft  \\\n",
       "Year                                                               \n",
       "1960-01-01   107840              154320    912100        1855400   \n",
       "1961-01-01   106670              156760    949600        1913000   \n",
       "1962-01-01   110860              164570    994300        2089600   \n",
       "1963-01-01   116470              174210   1086400        2297800   \n",
       "1964-01-01   130390              203050   1213200        2514400   \n",
       "\n",
       "            Vehicle_Theft  \n",
       "Year                       \n",
       "1960-01-01         328200  \n",
       "1961-01-01         336000  \n",
       "1962-01-01         366800  \n",
       "1963-01-01         408300  \n",
       "1964-01-01         472800  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#将Year的数据类型转换为 datetime64\n",
    "crime.Year = pd.to_datetime(crime.Year,format='%Y')\n",
    "#将列Year设置为数据框的索引\n",
    "crime = crime.set_index('Year',drop=True)\n",
    "crime.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960-01-01</th>\n",
       "      <td>179323175</td>\n",
       "      <td>288460</td>\n",
       "      <td>3095700</td>\n",
       "      <td>9110</td>\n",
       "      <td>17190</td>\n",
       "      <td>107840</td>\n",
       "      <td>154320</td>\n",
       "      <td>912100</td>\n",
       "      <td>1855400</td>\n",
       "      <td>328200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1961-01-01</th>\n",
       "      <td>182992000</td>\n",
       "      <td>289390</td>\n",
       "      <td>3198600</td>\n",
       "      <td>8740</td>\n",
       "      <td>17220</td>\n",
       "      <td>106670</td>\n",
       "      <td>156760</td>\n",
       "      <td>949600</td>\n",
       "      <td>1913000</td>\n",
       "      <td>336000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1962-01-01</th>\n",
       "      <td>185771000</td>\n",
       "      <td>301510</td>\n",
       "      <td>3450700</td>\n",
       "      <td>8530</td>\n",
       "      <td>17550</td>\n",
       "      <td>110860</td>\n",
       "      <td>164570</td>\n",
       "      <td>994300</td>\n",
       "      <td>2089600</td>\n",
       "      <td>366800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1963-01-01</th>\n",
       "      <td>188483000</td>\n",
       "      <td>316970</td>\n",
       "      <td>3792500</td>\n",
       "      <td>8640</td>\n",
       "      <td>17650</td>\n",
       "      <td>116470</td>\n",
       "      <td>174210</td>\n",
       "      <td>1086400</td>\n",
       "      <td>2297800</td>\n",
       "      <td>408300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1964-01-01</th>\n",
       "      <td>191141000</td>\n",
       "      <td>364220</td>\n",
       "      <td>4200400</td>\n",
       "      <td>9360</td>\n",
       "      <td>21420</td>\n",
       "      <td>130390</td>\n",
       "      <td>203050</td>\n",
       "      <td>1213200</td>\n",
       "      <td>2514400</td>\n",
       "      <td>472800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Population  Violent  Property  Murder  Forcible_Rape  Robbery  \\\n",
       "Year                                                                        \n",
       "1960-01-01   179323175   288460   3095700    9110          17190   107840   \n",
       "1961-01-01   182992000   289390   3198600    8740          17220   106670   \n",
       "1962-01-01   185771000   301510   3450700    8530          17550   110860   \n",
       "1963-01-01   188483000   316970   3792500    8640          17650   116470   \n",
       "1964-01-01   191141000   364220   4200400    9360          21420   130390   \n",
       "\n",
       "            Aggravated_assault  Burglary  Larceny_Theft  Vehicle_Theft  \n",
       "Year                                                                    \n",
       "1960-01-01              154320    912100        1855400         328200  \n",
       "1961-01-01              156760    949600        1913000         336000  \n",
       "1962-01-01              164570    994300        2089600         366800  \n",
       "1963-01-01              174210   1086400        2297800         408300  \n",
       "1964-01-01              203050   1213200        2514400         472800  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#删除名为Total的列\n",
    "del crime['Total']\n",
    "crime.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/s7/w2gl1bq96tnb0wq2g8344qy80000gn/T/ipykernel_70371/3951677694.py:3: FutureWarning: 'AS' is deprecated and will be removed in a future version, please use 'YS' instead.\n",
      "  crimes = crime.resample('10AS').sum()\n",
      "/var/folders/s7/w2gl1bq96tnb0wq2g8344qy80000gn/T/ipykernel_70371/3951677694.py:5: FutureWarning: 'AS' is deprecated and will be removed in a future version, please use 'YS' instead.\n",
      "  crimes['population'] = crime.resample('10AS').max\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "      <th>population</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960-01-01</th>\n",
       "      <td>1915053175</td>\n",
       "      <td>4134930</td>\n",
       "      <td>45160900</td>\n",
       "      <td>106180</td>\n",
       "      <td>236720</td>\n",
       "      <td>1633510</td>\n",
       "      <td>2158520</td>\n",
       "      <td>13321100</td>\n",
       "      <td>26547700</td>\n",
       "      <td>5292100</td>\n",
       "      <td>&lt;bound method Resampler.max of &lt;pandas.core.re...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1970-01-01</th>\n",
       "      <td>2121193298</td>\n",
       "      <td>9607930</td>\n",
       "      <td>91383800</td>\n",
       "      <td>192230</td>\n",
       "      <td>554570</td>\n",
       "      <td>4159020</td>\n",
       "      <td>4702120</td>\n",
       "      <td>28486000</td>\n",
       "      <td>53157800</td>\n",
       "      <td>9739900</td>\n",
       "      <td>&lt;bound method Resampler.max of &lt;pandas.core.re...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1980-01-01</th>\n",
       "      <td>2371370069</td>\n",
       "      <td>14074328</td>\n",
       "      <td>117048900</td>\n",
       "      <td>206439</td>\n",
       "      <td>865639</td>\n",
       "      <td>5383109</td>\n",
       "      <td>7619130</td>\n",
       "      <td>33073494</td>\n",
       "      <td>72040253</td>\n",
       "      <td>11935411</td>\n",
       "      <td>&lt;bound method Resampler.max of &lt;pandas.core.re...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1990-01-01</th>\n",
       "      <td>2612825258</td>\n",
       "      <td>17527048</td>\n",
       "      <td>119053499</td>\n",
       "      <td>211664</td>\n",
       "      <td>998827</td>\n",
       "      <td>5748930</td>\n",
       "      <td>10568963</td>\n",
       "      <td>26750015</td>\n",
       "      <td>77679366</td>\n",
       "      <td>14624418</td>\n",
       "      <td>&lt;bound method Resampler.max of &lt;pandas.core.re...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000-01-01</th>\n",
       "      <td>2947969117</td>\n",
       "      <td>13968056</td>\n",
       "      <td>100944369</td>\n",
       "      <td>163068</td>\n",
       "      <td>922499</td>\n",
       "      <td>4230366</td>\n",
       "      <td>8652124</td>\n",
       "      <td>21565176</td>\n",
       "      <td>67970291</td>\n",
       "      <td>11412834</td>\n",
       "      <td>&lt;bound method Resampler.max of &lt;pandas.core.re...</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Population   Violent   Property  Murder  Forcible_Rape  Robbery  \\\n",
       "Year                                                                          \n",
       "1960-01-01  1915053175   4134930   45160900  106180         236720  1633510   \n",
       "1970-01-01  2121193298   9607930   91383800  192230         554570  4159020   \n",
       "1980-01-01  2371370069  14074328  117048900  206439         865639  5383109   \n",
       "1990-01-01  2612825258  17527048  119053499  211664         998827  5748930   \n",
       "2000-01-01  2947969117  13968056  100944369  163068         922499  4230366   \n",
       "\n",
       "            Aggravated_assault  Burglary  Larceny_Theft  Vehicle_Theft  \\\n",
       "Year                                                                     \n",
       "1960-01-01             2158520  13321100       26547700        5292100   \n",
       "1970-01-01             4702120  28486000       53157800        9739900   \n",
       "1980-01-01             7619130  33073494       72040253       11935411   \n",
       "1990-01-01            10568963  26750015       77679366       14624418   \n",
       "2000-01-01             8652124  21565176       67970291       11412834   \n",
       "\n",
       "                                                   population  \n",
       "Year                                                           \n",
       "1960-01-01  <bound method Resampler.max of <pandas.core.re...  \n",
       "1970-01-01  <bound method Resampler.max of <pandas.core.re...  \n",
       "1980-01-01  <bound method Resampler.max of <pandas.core.re...  \n",
       "1990-01-01  <bound method Resampler.max of <pandas.core.re...  \n",
       "2000-01-01  <bound method Resampler.max of <pandas.core.re...  "
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#按照Year（每十年）对数据框进行分组并求和\n",
    "#按时间聚合参考博客：https://www.jb51.net/article/177325.htm\n",
    "crimes = crime.resample('10AS').sum()\n",
    "#人口是累计数，不能直接求和\n",
    "crimes['population'] = crime.resample('10AS').max\n",
    "crimes.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Population           2014-01-01\n",
       "Violent              1992-01-01\n",
       "Property             1991-01-01\n",
       "Murder               1991-01-01\n",
       "Forcible_Rape        1992-01-01\n",
       "Robbery              1991-01-01\n",
       "Aggravated_assault   1993-01-01\n",
       "Burglary             1980-01-01\n",
       "Larceny_Theft        1991-01-01\n",
       "Vehicle_Theft        1991-01-01\n",
       "dtype: datetime64[ns]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#何时是美国历史上生存最危险的年代？\n",
    "crime.idxmax()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 深度数据分析\n",
    "### 1. 计算犯罪率（每10万人）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算每10万人的犯罪率，更准确地反映犯罪趋势\n",
    "crime_rate = crime.copy()\n",
    "\n",
    "# 计算各类犯罪的犯罪率（每10万人）\n",
    "crime_rate['Violent_Rate'] = (crime['Violent'] / crime['Population']) * 100000\n",
    "crime_rate['Property_Rate'] = (crime['Property'] / crime['Population']) * 100000\n",
    "crime_rate['Murder_Rate'] = (crime['Murder'] / crime['Population']) * 100000\n",
    "crime_rate['Rape_Rate'] = (crime['Forcible_Rape'] / crime['Population']) * 100000\n",
    "crime_rate['Robbery_Rate'] = (crime['Robbery'] / crime['Population']) * 100000\n",
    "crime_rate['Assault_Rate'] = (crime['Aggravated_assault'] / crime['Population']) * 100000\n",
    "crime_rate['Burglary_Rate'] = (crime['Burglary'] / crime['Population']) * 100000\n",
    "crime_rate['Larceny_Rate'] = (crime['Larceny_Theft'] / crime['Population']) * 100000\n",
    "crime_rate['Vehicle_Theft_Rate'] = (crime['Vehicle_Theft'] / crime['Population']) * 100000\n",
    "\n",
    "# 显示犯罪率数据\n",
    "print(\"犯罪率统计（每10万人）：\")\n",
    "print(crime_rate[['Violent_Rate', 'Property_Rate', 'Murder_Rate', 'Robbery_Rate']].describe())\n",
    "crime_rate[['Violent_Rate', 'Property_Rate', 'Murder_Rate', 'Robbery_Rate']].head(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 时间序列趋势可视化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "# 设置中文字体和样式\n",
    "plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'SimHei', 'DejaVu Sans']\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "sns.set_style('whitegrid')\n",
    "\n",
    "# 创建图表：暴力犯罪率和财产犯罪率趋势\n",
    "fig, axes = plt.subplots(2, 1, figsize=(14, 10))\n",
    "\n",
    "# 暴力犯罪率趋势\n",
    "axes[0].plot(crime_rate.index, crime_rate['Violent_Rate'], linewidth=2, color='red', label='Violent Crime Rate')\n",
    "axes[0].set_title('Violent Crime Rate Trend (1960-2014)', fontsize=14, fontweight='bold')\n",
    "axes[0].set_ylabel('Rate per 100,000 people', fontsize=12)\n",
    "axes[0].legend()\n",
    "axes[0].grid(True, alpha=0.3)\n",
    "\n",
    "# 财产犯罪率趋势\n",
    "axes[1].plot(crime_rate.index, crime_rate['Property_Rate'], linewidth=2, color='blue', label='Property Crime Rate')\n",
    "axes[1].set_title('Property Crime Rate Trend (1960-2014)', fontsize=14, fontweight='bold')\n",
    "axes[1].set_ylabel('Rate per 100,000 people', fontsize=12)\n",
    "axes[1].set_xlabel('Year', fontsize=12)\n",
    "axes[1].legend()\n",
    "axes[1].grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. 各类暴力犯罪详细趋势对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 绘制各类暴力犯罪的趋势对比\n",
    "fig, ax = plt.subplots(figsize=(14, 7))\n",
    "\n",
    "ax.plot(crime_rate.index, crime_rate['Murder_Rate'], linewidth=2, label='Murder', marker='o', markersize=3)\n",
    "ax.plot(crime_rate.index, crime_rate['Rape_Rate'], linewidth=2, label='Rape', marker='s', markersize=3)\n",
    "ax.plot(crime_rate.index, crime_rate['Robbery_Rate'], linewidth=2, label='Robbery', marker='^', markersize=3)\n",
    "ax.plot(crime_rate.index, crime_rate['Assault_Rate'], linewidth=2, label='Aggravated Assault', marker='d', markersize=3)\n",
    "\n",
    "ax.set_title('Violent Crime Types Comparison (1960-2014)', fontsize=16, fontweight='bold')\n",
    "ax.set_ylabel('Rate per 100,000 people', fontsize=12)\n",
    "ax.set_xlabel('Year', fontsize=12)\n",
    "ax.legend(loc='best', fontsize=10)\n",
    "ax.grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. 各类财产犯罪详细趋势对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 绘制各类财产犯罪的趋势对比\n",
    "fig, ax = plt.subplots(figsize=(14, 7))\n",
    "\n",
    "ax.plot(crime_rate.index, crime_rate['Burglary_Rate'], linewidth=2, label='Burglary', marker='o', markersize=3)\n",
    "ax.plot(crime_rate.index, crime_rate['Larceny_Rate'], linewidth=2, label='Larceny-Theft', marker='s', markersize=3)\n",
    "ax.plot(crime_rate.index, crime_rate['Vehicle_Theft_Rate'], linewidth=2, label='Vehicle Theft', marker='^', markersize=3)\n",
    "\n",
    "ax.set_title('Property Crime Types Comparison (1960-2014)', fontsize=16, fontweight='bold')\n",
    "ax.set_ylabel('Rate per 100,000 people', fontsize=12)\n",
    "ax.set_xlabel('Year', fontsize=12)\n",
    "ax.legend(loc='best', fontsize=10)\n",
    "ax.grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. 犯罪率热力图分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建热力图数据：按年代分组\n",
    "crime_rate['Decade'] = (crime_rate.index.year // 10) * 10\n",
    "\n",
    "# 按年代计算平均犯罪率\n",
    "decade_avg = crime_rate.groupby('Decade')[[\n",
    "    'Murder_Rate', 'Rape_Rate', 'Robbery_Rate', 'Assault_Rate',\n",
    "    'Burglary_Rate', 'Larceny_Rate', 'Vehicle_Theft_Rate'\n",
    "]].mean()\n",
    "\n",
    "# 重命名列以便显示\n",
    "decade_avg.columns = ['Murder', 'Rape', 'Robbery', 'Assault', 'Burglary', 'Larceny', 'Vehicle Theft']\n",
    "\n",
    "# 绘制热力图\n",
    "fig, ax = plt.subplots(figsize=(12, 6))\n",
    "sns.heatmap(decade_avg.T, annot=True, fmt='.1f', cmap='YlOrRd', cbar_kws={'label': 'Rate per 100,000'}, ax=ax)\n",
    "ax.set_title('Crime Rates by Decade (Average per 100,000 people)', fontsize=14, fontweight='bold')\n",
    "ax.set_xlabel('Decade', fontsize=12)\n",
    "ax.set_ylabel('Crime Type', fontsize=12)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(\"\\nDecade Average Crime Rates:\")\n",
    "print(decade_avg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6. 犯罪率变化率分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算年度变化率（百分比）\n",
    "crime_change = crime_rate[[\n",
    "    'Violent_Rate', 'Property_Rate', 'Murder_Rate', \n",
    "    'Robbery_Rate', 'Burglary_Rate', 'Vehicle_Theft_Rate'\n",
    "]].pct_change() * 100\n",
    "\n",
    "# 绘制变化率\n",
    "fig, axes = plt.subplots(2, 1, figsize=(14, 10))\n",
    "\n",
    "# 暴力犯罪变化率\n",
    "axes[0].plot(crime_change.index, crime_change['Violent_Rate'], linewidth=1.5, color='red', alpha=0.7)\n",
    "axes[0].axhline(y=0, color='black', linestyle='--', linewidth=1)\n",
    "axes[0].fill_between(crime_change.index, crime_change['Violent_Rate'], 0, \n",
    "                      where=(crime_change['Violent_Rate'] > 0), alpha=0.3, color='red', label='Increase')\n",
    "axes[0].fill_between(crime_change.index, crime_change['Violent_Rate'], 0, \n",
    "                      where=(crime_change['Violent_Rate'] <= 0), alpha=0.3, color='green', label='Decrease')\n",
    "axes[0].set_title('Violent Crime Rate Year-over-Year Change (%)', fontsize=14, fontweight='bold')\n",
    "axes[0].set_ylabel('Change (%)', fontsize=12)\n",
    "axes[0].legend()\n",
    "axes[0].grid(True, alpha=0.3)\n",
    "\n",
    "# 财产犯罪变化率\n",
    "axes[1].plot(crime_change.index, crime_change['Property_Rate'], linewidth=1.5, color='blue', alpha=0.7)\n",
    "axes[1].axhline(y=0, color='black', linestyle='--', linewidth=1)\n",
    "axes[1].fill_between(crime_change.index, crime_change['Property_Rate'], 0, \n",
    "                      where=(crime_change['Property_Rate'] > 0), alpha=0.3, color='red', label='Increase')\n",
    "axes[1].fill_between(crime_change.index, crime_change['Property_Rate'], 0, \n",
    "                      where=(crime_change['Property_Rate'] <= 0), alpha=0.3, color='green', label='Decrease')\n",
    "axes[1].set_title('Property Crime Rate Year-over-Year Change (%)', fontsize=14, fontweight='bold')\n",
    "axes[1].set_ylabel('Change (%)', fontsize=12)\n",
    "axes[1].set_xlabel('Year', fontsize=12)\n",
    "axes[1].legend()\n",
    "axes[1].grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7. 犯罪类型相关性分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算各类犯罪之间的相关性\n",
    "correlation_data = crime_rate[[\n",
    "    'Murder_Rate', 'Rape_Rate', 'Robbery_Rate', 'Assault_Rate',\n",
    "    'Burglary_Rate', 'Larceny_Rate', 'Vehicle_Theft_Rate'\n",
    "]]\n",
    "\n",
    "correlation_matrix = correlation_data.corr()\n",
    "\n",
    "# 绘制相关性热力图\n",
    "fig, ax = plt.subplots(figsize=(10, 8))\n",
    "sns.heatmap(correlation_matrix, annot=True, fmt='.2f', cmap='coolwarm', \n",
    "            center=0, square=True, linewidths=1, cbar_kws={'label': 'Correlation'}, ax=ax)\n",
    "ax.set_title('Crime Types Correlation Matrix', fontsize=14, fontweight='bold')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(\"\\nCorrelation Matrix:\")\n",
    "print(correlation_matrix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8. 年代对比分析（箱线图）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建年代标签\n",
    "crime_rate_copy = crime_rate.copy()\n",
    "crime_rate_copy['Decade_Label'] = crime_rate_copy['Decade'].astype(str) + 's'\n",
    "\n",
    "# 绘制箱线图对比不同年代的犯罪率分布\n",
    "fig, axes = plt.subplots(2, 2, figsize=(16, 12))\n",
    "\n",
    "# 暴力犯罪率箱线图\n",
    "sns.boxplot(data=crime_rate_copy, x='Decade_Label', y='Violent_Rate', ax=axes[0, 0], palette='Reds')\n",
    "axes[0, 0].set_title('Violent Crime Rate Distribution by Decade', fontsize=12, fontweight='bold')\n",
    "axes[0, 0].set_xlabel('Decade', fontsize=10)\n",
    "axes[0, 0].set_ylabel('Rate per 100,000', fontsize=10)\n",
    "axes[0, 0].tick_params(axis='x', rotation=45)\n",
    "\n",
    "# 财产犯罪率箱线图\n",
    "sns.boxplot(data=crime_rate_copy, x='Decade_Label', y='Property_Rate', ax=axes[0, 1], palette='Blues')\n",
    "axes[0, 1].set_title('Property Crime Rate Distribution by Decade', fontsize=12, fontweight='bold')\n",
    "axes[0, 1].set_xlabel('Decade', fontsize=10)\n",
    "axes[0, 1].set_ylabel('Rate per 100,000', fontsize=10)\n",
    "axes[0, 1].tick_params(axis='x', rotation=45)\n",
    "\n",
    "# 谋杀率箱线图\n",
    "sns.boxplot(data=crime_rate_copy, x='Decade_Label', y='Murder_Rate', ax=axes[1, 0], palette='Oranges')\n",
    "axes[1, 0].set_title('Murder Rate Distribution by Decade', fontsize=12, fontweight='bold')\n",
    "axes[1, 0].set_xlabel('Decade', fontsize=10)\n",
    "axes[1, 0].set_ylabel('Rate per 100,000', fontsize=10)\n",
    "axes[1, 0].tick_params(axis='x', rotation=45)\n",
    "\n",
    "# 抢劫率箱线图\n",
    "sns.boxplot(data=crime_rate_copy, x='Decade_Label', y='Robbery_Rate', ax=axes[1, 1], palette='Purples')\n",
    "axes[1, 1].set_title('Robbery Rate Distribution by Decade', fontsize=12, fontweight='bold')\n",
    "axes[1, 1].set_xlabel('Decade', fontsize=10)\n",
    "axes[1, 1].set_ylabel('Rate per 100,000', fontsize=10)\n",
    "axes[1, 1].tick_params(axis='x', rotation=45)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9. 犯罪高峰期分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 找出各类犯罪的峰值年份和数值\n",
    "peak_analysis = pd.DataFrame({\n",
    "    'Crime_Type': ['Violent', 'Property', 'Murder', 'Rape', 'Robbery', 'Assault', 'Burglary', 'Larceny', 'Vehicle Theft'],\n",
    "    'Peak_Year': [\n",
    "        crime_rate['Violent_Rate'].idxmax(),\n",
    "        crime_rate['Property_Rate'].idxmax(),\n",
    "        crime_rate['Murder_Rate'].idxmax(),\n",
    "        crime_rate['Rape_Rate'].idxmax(),\n",
    "        crime_rate['Robbery_Rate'].idxmax(),\n",
    "        crime_rate['Assault_Rate'].idxmax(),\n",
    "        crime_rate['Burglary_Rate'].idxmax(),\n",
    "        crime_rate['Larceny_Rate'].idxmax(),\n",
    "        crime_rate['Vehicle_Theft_Rate'].idxmax()\n",
    "    ],\n",
    "    'Peak_Rate': [\n",
    "        crime_rate['Violent_Rate'].max(),\n",
    "        crime_rate['Property_Rate'].max(),\n",
    "        crime_rate['Murder_Rate'].max(),\n",
    "        crime_rate['Rape_Rate'].max(),\n",
    "        crime_rate['Robbery_Rate'].max(),\n",
    "        crime_rate['Assault_Rate'].max(),\n",
    "        crime_rate['Burglary_Rate'].max(),\n",
    "        crime_rate['Larceny_Rate'].max(),\n",
    "        crime_rate['Vehicle_Theft_Rate'].max()\n",
    "    ],\n",
    "    'Latest_Rate_2014': [\n",
    "        crime_rate['Violent_Rate'].iloc[-1],\n",
    "        crime_rate['Property_Rate'].iloc[-1],\n",
    "        crime_rate['Murder_Rate'].iloc[-1],\n",
    "        crime_rate['Rape_Rate'].iloc[-1],\n",
    "        crime_rate['Robbery_Rate'].iloc[-1],\n",
    "        crime_rate['Assault_Rate'].iloc[-1],\n",
    "        crime_rate['Burglary_Rate'].iloc[-1],\n",
    "        crime_rate['Larceny_Rate'].iloc[-1],\n",
    "        crime_rate['Vehicle_Theft_Rate'].iloc[-1]\n",
    "    ]\n",
    "})\n",
    "\n",
    "# 计算从峰值到2014年的下降百分比\n",
    "peak_analysis['Decline_from_Peak_%'] = ((peak_analysis['Peak_Rate'] - peak_analysis['Latest_Rate_2014']) / peak_analysis['Peak_Rate'] * 100)\n",
    "\n",
    "print(\"\\n=== Crime Peak Analysis ===\")\n",
    "print(peak_analysis.to_string(index=False))\n",
    "\n",
    "# 可视化峰值对比\n",
    "fig, ax = plt.subplots(figsize=(14, 7))\n",
    "x = range(len(peak_analysis))\n",
    "width = 0.35\n",
    "\n",
    "bars1 = ax.bar([i - width/2 for i in x], peak_analysis['Peak_Rate'], width, label='Peak Rate', alpha=0.8, color='red')\n",
    "bars2 = ax.bar([i + width/2 for i in x], peak_analysis['Latest_Rate_2014'], width, label='2014 Rate', alpha=0.8, color='green')\n",
    "\n",
    "ax.set_xlabel('Crime Type', fontsize=12)\n",
    "ax.set_ylabel('Rate per 100,000 people', fontsize=12)\n",
    "ax.set_title('Peak Crime Rates vs 2014 Rates', fontsize=14, fontweight='bold')\n",
    "ax.set_xticks(x)\n",
    "ax.set_xticklabels(peak_analysis['Crime_Type'], rotation=45, ha='right')\n",
    "ax.legend()\n",
    "ax.grid(True, alpha=0.3, axis='y')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10. 综合趋势分析总结"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算关键统计数据\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"US CRIME DATA ANALYSIS SUMMARY (1960-2014)\")\n",
    "print(\"=\"*60)\n",
    "\n",
    "print(\"\\n1. OVERALL TRENDS:\")\n",
    "print(f\"   - Population Growth: {crime['Population'].iloc[0]:,} → {crime['Population'].iloc[-1]:,}\")\n",
    "print(f\"   - Growth Rate: {((crime['Population'].iloc[-1] / crime['Population'].iloc[0]) - 1) * 100:.1f}%\")\n",
    "\n",
    "print(\"\\n2. VIOLENT CRIME RATE (per 100,000):\")\n",
    "print(f\"   - 1960: {crime_rate['Violent_Rate'].iloc[0]:.1f}\")\n",
    "print(f\"   - Peak: {crime_rate['Violent_Rate'].max():.1f} in {crime_rate['Violent_Rate'].idxmax().year}\")\n",
    "print(f\"   - 2014: {crime_rate['Violent_Rate'].iloc[-1]:.1f}\")\n",
    "print(f\"   - Change from peak: {((crime_rate['Violent_Rate'].iloc[-1] / crime_rate['Violent_Rate'].max()) - 1) * 100:.1f}%\")\n",
    "\n",
    "print(\"\\n3. PROPERTY CRIME RATE (per 100,000):\")\n",
    "print(f\"   - 1960: {crime_rate['Property_Rate'].iloc[0]:.1f}\")\n",
    "print(f\"   - Peak: {crime_rate['Property_Rate'].max():.1f} in {crime_rate['Property_Rate'].idxmax().year}\")\n",
    "print(f\"   - 2014: {crime_rate['Property_Rate'].iloc[-1]:.1f}\")\n",
    "print(f\"   - Change from peak: {((crime_rate['Property_Rate'].iloc[-1] / crime_rate['Property_Rate'].max()) - 1) * 100:.1f}%\")\n",
    "\n",
    "print(\"\\n4. MURDER RATE (per 100,000):\")\n",
    "print(f\"   - 1960: {crime_rate['Murder_Rate'].iloc[0]:.2f}\")\n",
    "print(f\"   - Peak: {crime_rate['Murder_Rate'].max():.2f} in {crime_rate['Murder_Rate'].idxmax().year}\")\n",
    "print(f\"   - 2014: {crime_rate['Murder_Rate'].iloc[-1]:.2f}\")\n",
    "print(f\"   - Change from peak: {((crime_rate['Murder_Rate'].iloc[-1] / crime_rate['Murder_Rate'].max()) - 1) * 100:.1f}%\")\n",
    "\n",
    "print(\"\\n5. KEY INSIGHTS:\")\n",
    "print(\"   - Most crime types peaked in the early 1990s\")\n",
    "print(\"   - Significant decline in crime rates from 1990s to 2014\")\n",
    "print(\"   - Property crimes are much more common than violent crimes\")\n",
    "print(\"   - Strong correlation between different crime types\")\n",
    "print(\"\\n\" + \"=\"*60)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 11. 滚动平均趋势分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算5年滚动平均，平滑趋势\n",
    "rolling_window = 5\n",
    "\n",
    "crime_rate['Violent_Rate_MA'] = crime_rate['Violent_Rate'].rolling(window=rolling_window, center=True).mean()\n",
    "crime_rate['Property_Rate_MA'] = crime_rate['Property_Rate'].rolling(window=rolling_window, center=True).mean()\n",
    "crime_rate['Murder_Rate_MA'] = crime_rate['Murder_Rate'].rolling(window=rolling_window, center=True).mean()\n",
    "\n",
    "# 绘制原始数据和滚动平均对比\n",
    "fig, axes = plt.subplots(3, 1, figsize=(14, 12))\n",
    "\n",
    "# 暴力犯罪率\n",
    "axes[0].plot(crime_rate.index, crime_rate['Violent_Rate'], alpha=0.4, linewidth=1, label='Original', color='red')\n",
    "axes[0].plot(crime_rate.index, crime_rate['Violent_Rate_MA'], linewidth=2.5, label=f'{rolling_window}-Year Moving Average', color='darkred')\n",
    "axes[0].set_title('Violent Crime Rate: Original vs Moving Average', fontsize=14, fontweight='bold')\n",
    "axes[0].set_ylabel('Rate per 100,000', fontsize=11)\n",
    "axes[0].legend()\n",
    "axes[0].grid(True, alpha=0.3)\n",
    "\n",
    "# 财产犯罪率\n",
    "axes[1].plot(crime_rate.index, crime_rate['Property_Rate'], alpha=0.4, linewidth=1, label='Original', color='blue')\n",
    "axes[1].plot(crime_rate.index, crime_rate['Property_Rate_MA'], linewidth=2.5, label=f'{rolling_window}-Year Moving Average', color='darkblue')\n",
    "axes[1].set_title('Property Crime Rate: Original vs Moving Average', fontsize=14, fontweight='bold')\n",
    "axes[1].set_ylabel('Rate per 100,000', fontsize=11)\n",
    "axes[1].legend()\n",
    "axes[1].grid(True, alpha=0.3)\n",
    "\n",
    "# 谋杀率\n",
    "axes[2].plot(crime_rate.index, crime_rate['Murder_Rate'], alpha=0.4, linewidth=1, label='Original', color='orange')\n",
    "axes[2].plot(crime_rate.index, crime_rate['Murder_Rate_MA'], linewidth=2.5, label=f'{rolling_window}-Year Moving Average', color='darkorange')\n",
    "axes[2].set_title('Murder Rate: Original vs Moving Average', fontsize=14, fontweight='bold')\n",
    "axes[2].set_ylabel('Rate per 100,000', fontsize=11)\n",
    "axes[2].set_xlabel('Year', fontsize=11)\n",
    "axes[2].legend()\n",
    "axes[2].grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
